package com.uu.safeguard.controller;

import com.uu.safeguard.common.Constant;
import com.uu.safeguard.result.Result;
import com.uu.safeguard.result.ResultFactory;
import com.uu.safeguard.service.ChargeLogService;
import com.uu.safeguard.service.MemberRechargeLogService;
import com.uu.safeguard.service.MemberService;
import com.uu.safeguard.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * (Member)表控制层
 *
 * @author makejava
 * @since 2021-07-05 16:14:26
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    private Logger logger = LoggerFactory.getLogger(MemberController.class);
    /**
     * 服务对象
     */
    @Resource
    private MemberService memberService;

    @Resource
    private MemberRechargeLogService memberRechargeLogService;

    @Resource
    private ChargeLogService chargeLogService;
    /***
     * @Description: 刷新token
     * @Param: [token, operatorMemberSn]
     **/
    @PostMapping("refreshToken")
    public Result refreshToken(@RequestHeader("token")String token, @RequestHeader("operatorMemberSn") String operatorMemberSn) throws UnsupportedEncodingException {
        String memberSn = JwtUtil.getUserId(token);
        token = JwtUtil.sign(memberSn, Constant.TOKEN_SECRET);

        List<String> roleIds = new ArrayList();
        if(null != operatorMemberSn && null != memberSn && StringUtils.isNotBlank(operatorMemberSn) && StringUtils.isNotBlank(memberSn) && operatorMemberSn.equals(memberSn) ){
            roleIds.add("3");
        }
        if(!operatorMemberSn.equals(memberSn)){
            //遍历当前身份
            DbUtil db = new DbUtil();
            List<Map> staffList = db.table("staff").where(new ArrayList() {{
                add(new ArrayList() {{
                    add("operator_member_sn");
                    add("=");
                    add(operatorMemberSn);
                }});
                add(new ArrayList() {{
                    add("staff_member_sn");
                    add("=");
                    add(memberSn);
                }});
                add(new ArrayList() {{
                    add("state");
                    add("=");
                    add(1);
                }});
            }}).select("*");
            roleIds = new ArrayList();
            for (int i = 0; i < staffList.size(); i++) {
                Map detail = staffList.get(i);
                roleIds.add(detail.get("role_id").toString());
            }
        }


        Map data = new HashMap();
        data.put("token",token);
        data.put("role_ids",roleIds);
        return ResultFactory.buildSuccessResult(data);

    }
    /**
     * @Description: 用户搜索
     * @Param: [params]
     **/
    @PostMapping("/searchMsg")
    public Result list(@RequestParam Map<String, String> params){
        String memberSn = params.get("member_sn");
        if(StringUtils.isEmpty(params.get("member_sn"))){
            return ResultFactory.buildFailResult("请输入用户账号");
        }
        LinkedHashMap<String, Object> map = memberService.searchMemberBySn(memberSn);
        if(null == map){
            return ResultFactory.buildFailResult("查询结果为空");
        }
        map.put("create_time", WsDateUtil.stampToDate(map.get("create_time").toString()));
        //用户正在充电列表
        List<LinkedHashMap<String, Object>> memberChargeList = chargeLogService.searchMemberChargeList(memberSn);
        List newMemberChargeList = new ArrayList<>();
        //redis
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(0);
        for (int i = 0; i <memberChargeList.size(); i++) {
            //查询缓存中是否存在.remove(key)
            String redisKey = memberChargeList.get(i).get("socket_sn")+"";
            logger.info("key："+ redisKey);
            if(jedis.exists(redisKey)){
                logger.info("存在的key："+ redisKey);
                Map<String, String> redisParam = jedis.hgetAll(redisKey);
                logger.info("判断："+memberChargeList.get(i).get("id").toString()+"--"+redisParam.get("charge_log_id"));
                if(memberChargeList.get(i).get("id").toString().equals(redisParam.get("charge_log_id"))) {
                    long duration = (System.currentTimeMillis() - Long.valueOf(String.valueOf(memberChargeList.get(i).get("start_time"))));
                    logger.info("实时充电时长(格式化)：" + WsDateUtil.getHMS(duration));
                    memberChargeList.get(i).put("duration", WsDateUtil.getHMS(duration));
                    memberChargeList.get(i).put("charge_log_id", redisParam.get("charge_log_id"));
                    memberChargeList.get(i).put("power_value", redisParam.get("power_value"));
                    memberChargeList.get(i).put("money_total", CommonUtil.formatMoney(redisParam.get("money_total"), 2));
                    memberChargeList.get(i).put("charging_mode", redisParam.get("charging_mode"));
                    newMemberChargeList.add(memberChargeList.get(i));
                    logger.info("redis:" + redisParam.toString());
                }else{
                    logger.info("charge_log_id 不相同就移除："+ memberChargeList.get(i));
                    logger.info("移除的 key："+ redisKey);
                    //key 不存在就移除
                    //memberChargeList.remove(i);
                }
            }else{
                logger.info("key 不存在就移除："+ memberChargeList.get(i));
                logger.info("移除的 key："+ redisKey);
                //key 不存在就移除
                //memberChargeList.remove(i);
            }
        }
        //关闭连接
        JedisUtil.close(jedis);
        map.put("ChargingList",newMemberChargeList);
        return ResultFactory.buildSuccessResult(map);
    }
}